﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity.Admin;
using Web.Framework;
using Core;

namespace Service
{
    public class ParameterRuleService : BaseService<ParameterRule>
    {
        public ParameterRuleService(DBEntities db)
            : base(db)
        { }

        public override ParameterRule Create(ParameterRule entity)
        {
            if (string.IsNullOrWhiteSpace(entity.ID))
            {
                entity.ID = Guid.NewGuid().ToString();
            }
            Nullable<int> maxRuleLevel = db.ParameterRules.Max(p => p.RuleLevel);
            entity.RuleLevel = maxRuleLevel.HasValue ? maxRuleLevel.Value + 1 : 1;
            return base.Create(entity);
        }

        public override ParameterRule Save(ParameterRule entity)
        {
            return base.Save(entity);
        }

        public ParameterRule CreateOrUpdate(ParameterRule entity)
        {
            if (!entity.RulePath.StartsWith("/"))
            {
                throw new ModelCheckException("RulePath", "匹配路径必须以\"/\"开始");
            }
            if (string.IsNullOrWhiteSpace(entity.ID))
            {
                return Create(entity);
            }
            else
            {
                return Save(entity);
            }
        }
    }
}
